package com.chexiehui.jc.ui.activity;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aries.ui.view.radius.RadiusTextView;
import com.aries.ui.widget.action.sheet.UIActionSheetDialog;
import com.blankj.utilcode.util.StringUtils;
import com.chexiehui.jc.Constants;
import com.chexiehui.jc.R;
import com.chexiehui.jc.base.BaseModel;
import com.chexiehui.jc.base.BaseMvpActivity;
import com.chexiehui.jc.entity.CarSeriesInfo;
import com.chexiehui.jc.entity.ForumInfo;
import com.chexiehui.jc.event.CreateForumEvent;
import com.chexiehui.jc.mvp.forum.ForumEditCovenant;
import com.chexiehui.jc.mvp.forum.ForumEditPresenter;
import com.chexiehui.jc.utils.AliossUtil;
import com.chexiehui.jc.utils.BundleBuilder;
import com.chexiehui.jc.utils.GlideEngine;
import com.chexiehui.jc.utils.GlideUtil;
import com.chexiehui.jc.utils.NoDoubleClickUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.style.PictureWindowAnimationStyle;
import com.luck.picture.lib.tools.LocalMediaUtils;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.PermissionListener;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;

/**
 * 编辑论坛
 */
public class ForumEditActivity extends BaseMvpActivity<ForumEditPresenter> implements ForumEditCovenant.View {
    @BindView(R.id.tv_forum_type)
    TextView tvForumType;
    @BindView(R.id.ll_forum_type_panel)
    LinearLayout llForumTypePanel;
    @BindView(R.id.tv_forum_series)
    TextView tvForumSeries;
    @BindView(R.id.ll_car_series_panel)
    LinearLayout llCarSeriesPanel;
    @BindView(R.id.et_forum_name)
    EditText etForumName;
    @BindView(R.id.iv_forum_head)
    ImageView ivForumHead;
    @BindView(R.id.rl_forum_head_panel)
    RelativeLayout rlForumHeadPanel;
    @BindView(R.id.et_forum_introduce)
    EditText etForumIntroduce;
    @BindView(R.id.tv_introduce_count)
    TextView tvIntroduceCount;
    @BindView(R.id.rtv_save_submit)
    RadiusTextView rtvSaveSubmit;
    @BindView(R.id.tv_resume_reason)
    TextView tvResumeReason;
    @BindView(R.id.ll_resume_reason)
    LinearLayout llResumeReason;

    private ForumInfo forumInfo;

    private int maxTextCount = 200;

    @Override
    protected void setTitleBar() {
        titleBar.setTitleMainText("论坛详情");
    }

    @Override
    protected void beforeSetView() {
        Bundle bundle = getIntent().getExtras();
        if(bundle != null){
            forumInfo = (ForumInfo) bundle.getSerializable("entity");
        }
        if(forumInfo == null){
            forumInfo = new ForumInfo();
        }
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_forum_create;
    }

    @Override
    protected void initView(Bundle var1) {
        setChooseTypeInfo();
        setImageHead();
        etForumName.setText(forumInfo.getName());
        etForumIntroduce.setText(forumInfo.getIntroduction());
        etForumIntroduce.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                etForumIntroduce.removeTextChangedListener(this);//**** 注意的地方
                if(s.length() == 0){
                    tvIntroduceCount.setText(maxTextCount + "字以内");
                }else if (s.length() > maxTextCount) {
                    etForumIntroduce.setText(s.toString().substring(0, maxTextCount));
                    etForumIntroduce.setSelection(maxTextCount);
                    tvIntroduceCount.setText(maxTextCount + "字以内");
                } else {
                    tvIntroduceCount.setText(s.length() + "/" + maxTextCount + "字");
                }
                etForumIntroduce.addTextChangedListener(this);//****  注意的地方
            }
            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        llResumeReason.setVisibility(View.GONE);
        if(forumInfo.getStatus() == 1){
            rtvSaveSubmit.setText("重新提交");
            rtvSaveSubmit.setEnabled(true);
            etForumName.setEnabled(true);
            etForumIntroduce.setEnabled(true);
        }else if(forumInfo.getStatus() == 2){
            rtvSaveSubmit.setText("重新申请");
            rtvSaveSubmit.setEnabled(true);
            etForumName.setEnabled(true);
            etForumIntroduce.setEnabled(true);
            llResumeReason.setVisibility(View.VISIBLE);
            tvResumeReason.setText(forumInfo.getOpinion());
        }else{
            rtvSaveSubmit.setText("审核中");
            rtvSaveSubmit.setEnabled(false);
            etForumName.setEnabled(false);
            etForumIntroduce.setEnabled(false);
        }
    }

    private void setChooseTypeInfo(){
        llCarSeriesPanel.setVisibility(forumInfo.getType().equals("0") ? View.VISIBLE : View.GONE);
        tvForumSeries.setText(forumInfo.getSeriesName());
        tvForumType.setText(forumInfo.getTypeStr());
    }

    @OnClick({R.id.ll_forum_type_panel, R.id.ll_car_series_panel,
            R.id.rl_forum_head_panel, R.id.rtv_save_submit})
    public void onViewClicked(View view) {
        if(forumInfo.getStatus() == 0){
            return;
        }
        if(NoDoubleClickUtils.isDoubleClick()){
             return;
        }
        switch (view.getId()) {
            case R.id.ll_forum_type_panel:
                showChooseForumDialog();
                break;
            case R.id.ll_car_series_panel:
                startActivityForResult(ChooseCarModelActivity.class, 20,
                        new BundleBuilder().putInt("chooseLevel", 2).create());
                break;
            case R.id.rl_forum_head_panel:
                applyPhotoPermission(100);
                break;
            case R.id.rtv_save_submit:
                mvpPresenter.submit();
                break;
        }
    }

    private void applyPhotoPermission(final int code) {
        AndPermission.with(this)
                .permission(Permission.CAMERA, Permission.STORAGE)
                .callback(new PermissionListener() {
                    @Override
                    public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
                        PictureWindowAnimationStyle windowAnimationStyle = new PictureWindowAnimationStyle();
                        windowAnimationStyle.ofAllAnimation(R.anim.picture_anim_up_in, R.anim.picture_anim_down_out);
                        // 进入相册 以下是例子：不需要的api可以不写
                        PictureSelector.create(mContext)
                                .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                                .loadImageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项
                                .theme(R.style.picture_QQ_style)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style v2.3.3后 建议使用setPictureStyle()动态方式
                                .setPictureWindowAnimationStyle(windowAnimationStyle)// 自定义相册启动退出动画
                                .imageSpanCount(4)// 每行显示个数
                                .isReturnEmpty(false)// 未选择数据时点击按钮是否可以返回
                                .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)// 设置相册Activity方向，不设置默认使用系统
                                .isOriginalImageControl(false)// 是否显示原图控制按钮，如果设置为true则用户可以自由选择是否使用原图，压缩、裁剪功能将会失效
                                .selectionMode(PictureConfig.SINGLE)// 多选 or 单选
                                .isSingleDirectReturn(true)// 单选模式下是否直接返回，PictureConfig.SINGLE模式下有效
                                .previewImage(true)// 是否可预览图片
                                .isCamera(true)// 是否显示拍照按钮
                                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                                .enableCrop(false)// 是否裁剪
                                .showCropFrame(true)
                                .freeStyleCropEnabled(false)
                                .scaleEnabled(false)
                                .showCropGrid(false)
                                .showCropFrame(true)
                                .compress(true)// 是否压缩
                                .compressQuality(90)// 图片压缩后输出质量 0~ 100
                                .synOrAsy(false)//同步false或异步true 压缩 默认同步
                                .queryMaxFileSize(20)// 只查多少M以内的图片、视频、音频  单位M
                                .isGif(false)// 是否显示gif图片
                                .previewEggs(true)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中)
                                .minimumCompressSize(100)// 小于100kb的图片不压缩
                                .recordVideoSecond(60)//录制视频秒数 默认60s
                                .forResult(code);//结果回调onActivityResult code*/
                    }

                    @Override
                    public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
                        if (AndPermission.hasAlwaysDeniedPermission(mContext, deniedPermissions)) {
                            AndPermission.defaultSettingDialog(mContext, Constants.REQUEST_CODE_CARAME).show();
                        } else {
                            showToast(getStringSource(R.string.app_name) + "需要您授权打开相机和相册的权限");
                        }
                    }
                })
                .requestCode(Constants.REQUEST_CODE_CARAME)
                .rationale((requestCode, rationale) -> AndPermission.rationaleDialog(mContext, rationale).show()).start();
    }

    private void showChooseForumDialog() {
        String[] items = new String[]{"车系论坛", "主题论坛", "地区论坛"};
        UIActionSheetDialog dialog = new UIActionSheetDialog.ListIOSBuilder(mContext)
                .addItems(items)
                .setTitle("选择论坛类型")
                .setOnItemClickListener((dialog1, itemView, position) -> {
                    dialog1.dismiss();
                    chooseFormIndex(position);
                })
                .create();
        dialog.show();
    }

    private void chooseFormIndex(int position) {
        forumInfo.setType(position + "");
        setChooseTypeInfo();
        if (position == 0) {
            startActivityForResult(ChooseCarModelActivity.class, 20,
                    new BundleBuilder().putInt("chooseLevel", 2).create());
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 20:
                if (resultCode == RESULT_OK) {
                    if (data != null) {
                        CarSeriesInfo seriesInfo = (CarSeriesInfo) data.getSerializableExtra("seriesInfo");
                        if (seriesInfo != null) {
                            forumInfo.setSeriesId(seriesInfo.getId());
                            forumInfo.setSeriesName(seriesInfo.getName());
                            setChooseTypeInfo();
                        }
                    }
                }
                break;
            case 100:{
                List<LocalMedia> selectedPhotoList = PictureSelector.obtainMultipleResult(data);
                if (selectedPhotoList.size() > 0) {
                    String path = LocalMediaUtils.getLocalPath(selectedPhotoList.get(0));
                    mvpPresenter.uploadImage(path);
                }
            }
            break;
        }
    }

    private void setImageHead(){
        if(StringUtils.isTrimEmpty(forumInfo.getIcon())){
            ivForumHead.setVisibility(View.GONE);
        }else{
            ivForumHead.setVisibility(View.VISIBLE);
            GlideUtil.loadImageViewCrop(mContext, AliossUtil.getEndPointFileUrl(forumInfo.getIcon()), ivForumHead,
                    R.drawable.shape_square, R.drawable.shape_square);
        }
    }

    @Override
    protected ForumEditPresenter createPresenter() {
        return new ForumEditPresenter(this);
    }

    @Override
    public void onUploadImageSuccess(BaseModel<String> successResult) {
        forumInfo.setIcon(successResult.getData());
        setImageHead();
    }

    @Override
    public void onUploadImageFailure(BaseModel<Object> failureResult) {
        showToast(failureResult.getResultInfo());
        setImageHead();
    }

    @Override
    public void onSubmitSuccess(BaseModel<Object> successResult) {
        showToast(successResult.getResultInfo());
        EventBus.getDefault().post(new CreateForumEvent());
        onBackPressed();
    }

    @Override
    public void onSubmitFailure(BaseModel<Object> failureResult) {
        showToast(failureResult.getResultInfo());
    }

    @Override
    public String getForumId() {
        return forumInfo.getId();
    }

    @Override
    public String getForumType() {
        return forumInfo.getType();
    }

    @Override
    public String getForumSeries() {
        return forumInfo.getSeriesId();
    }

    @Override
    public String getForumName() {
        return etForumName.getText().toString().trim();
    }

    @Override
    public String getForumHead() {
        return forumInfo.getIcon();
    }

    @Override
    public String getForumIntroduce() {
        return etForumIntroduce.getText().toString().trim();
    }
}
